package com.hades.servlet;

import com.hades.util.CookieUtils;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class CookieServlet extends BaseServlet{
    protected void createCookie(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Cookie cookie = new Cookie("key1","value1");
        resp.addCookie(cookie);
        Cookie cookie2 = new Cookie("key2","value2");
        resp.addCookie(cookie2);
        resp.getWriter().write("Cookie已创建<br/>");
    }

    protected void getCookie(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Cookie[] cookies = req.getCookies();
        for (Cookie cookie : cookies) {
            resp.getWriter().write("Cookie["+cookie.getName()+"="+cookie.getValue()+"]<br/>");
        }
        Cookie cookieIWant = CookieUtils.findCookie("key1",cookies);
        if(cookieIWant != null){
            resp.getWriter().write("找到了需要的cookie<br/>");
        }
    }
    protected void updateCookie(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Cookie cookie = new Cookie("key1","updateValue1");
        resp.addCookie(cookie);
        resp.getWriter().write("Cookie值已修改<br/>");
    }

    protected void defaultLife(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Cookie cookie = new Cookie("defaultLife","defaultLife");
        cookie.setMaxAge(-1);
        resp.addCookie(cookie);
    }

    protected void deleteNow(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Cookie cookie = CookieUtils.findCookie("key2",req.getCookies());
        if(cookie != null){
            cookie.setMaxAge(0);
            resp.addCookie(cookie);
            resp.getWriter().write("key2的cookie已被删除<br/>");
        }
    }

    protected void liveOneHour(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Cookie cookie = new Cookie("lifeOneHour","lifeOneHour");
        cookie.setMaxAge(60 * 60);
        resp.addCookie(cookie);
        resp.getWriter().write("创建了一个存活时长为1小时的cookie<br/>");
    }

    protected void testPath(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Cookie cookie = new Cookie("path1","path1");
        cookie.setPath(req.getContextPath() + "/abc");
        resp.addCookie(cookie);
        resp.getWriter().write("创建了一个带有Path路径的cookie");
    }
}
